package com.example.gridviewexample;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity implements OnScrollListener,
		OnItemClickListener {

	private GridView gv;
	private GridViewAdapter mAdapter;

	private static String URL = "http://dhuynh.net76.net/review_1.JSON";

	private static final String TAG_DATA = "data";
	private static final String TAG_ID = "id";
	private static final String TAG_TITLE = "title";

	JSONArray data = null;
	ArrayList<HashMap<String, String>> dataList;
	JSONParser jParser;
	JSONObject json;

	ProgressDialog pDialog;
	int current_page = 1;
	private int lastOffset = 0;

	LinearLayout loadMore;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		gv = (GridView) findViewById(R.id.gridView1);
		loadMore = (LinearLayout) findViewById(R.id.loading);

		dataList = new ArrayList<HashMap<String, String>>();
		jParser = new JSONParser();
		json = jParser.getJSONFromUrl(URL);
		try {
			data = json.getJSONArray(TAG_DATA);
			for (int i = 0; i <= data.length(); i++) {
				JSONObject d = data.getJSONObject(i);

				String id = d.getString(TAG_ID);
				String title = d.getString(TAG_TITLE);

				HashMap<String, String> map = new HashMap<String, String>();

				map.put(TAG_ID, id);
				map.put(TAG_TITLE, title);

				dataList.add(map);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		mAdapter = new GridViewAdapter(this, dataList);
		gv.setAdapter(mAdapter);
		gv.setOnItemClickListener(this);
		gv.setOnScrollListener(this);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		boolean isEndOfListReached = firstVisibleItem + visibleItemCount >= totalItemCount;
		boolean isOffsetRequested = lastOffset >= totalItemCount;

		if (isEndOfListReached && !isOffsetRequested) {
			lastOffset = totalItemCount;
			new LoadMoreListView().execute();
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	private class LoadMoreListView extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// increment current page
					current_page += 1;

					// Next page request
					URL = "http://dhuynh.net76.net/review_" + current_page
							+ ".JSON";

					json = jParser.getJSONFromUrl(URL);
					try {
						data = json.getJSONArray(TAG_DATA);
						for (int i = 0; i <= data.length(); i++) {
							JSONObject d = data.getJSONObject(i);

							String id = d.getString(TAG_ID);
							String title = d.getString(TAG_TITLE);

							HashMap<String, String> map = new HashMap<String, String>();

							map.put(TAG_ID, id);
							map.put(TAG_TITLE, title);

							dataList.add(map);
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}

					int currentPosition = gv.getFirstVisiblePosition();
					mAdapter = new GridViewAdapter(MainActivity.this, dataList);
					gv.setAdapter(mAdapter);

					gv.setSelection(currentPosition);
				}
			});
			return (null);
		}

		@Override
		protected void onPostExecute(Void result) {
			loadMore.setVisibility(View.INVISIBLE);
		}

		@Override
		protected void onPreExecute() {
			loadMore.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Toast.makeText(getApplicationContext(), "position: " + position,
				Toast.LENGTH_LONG).show();
	}
}
